import os
import time
import uuid
from datetime import datetime, timedelta, date

import xlrd, calendar
from django.db.models import Q, Count
from django.utils import timezone
from django.core.paginator import Paginator, PageNotAnInteger
from django.db import connection
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
# Create your views here.
from NewFlowLogic.models import CheckInInformation, ThreePartyAttendanceInformation
from administrative.models import Topics, Company, Topicsattachments, VehicleApply
from administrative.utils import send_mssage
from announcements import public_file
from correspondence.models import InboxInfo, InboxInfoPeople
from finance.models import CheckWorkAttendance, CheckWorkTable, CheckWorkLaborDispatch, BusinessContract, \
    CheckWorkRecord, TravelApply
from personal_center.models import User, Scheduling, SortLine
import json, re

from personnel.AutomaticScheduling import AutomaticScheduling, create_calendar
from personnel.models import DutyTime
from personnel.mysql_data import select_echarts_data
from static.personnel.timing_file.SchedulingProcedure import Scheduling_Procedure



class issue_statement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        year = request.GET.get('year', datetime.now().strftime("%Y"))
        month = request.GET.get('month', '')
        dept = request.GET.get('dept', '')

        yb_obj = Topics.objects.filter(~Q(state__in=['cg', 'cancel', 'recall']), type="yb", create_time__year=year)
        yb_wj_obj = yb_obj.filter(state="done")

        if month and month != '请选择月份':
            yb_obj = yb_obj.filter(create_time__month=month)
        if dept and dept != '请选择部门':
            yb_obj = yb_obj.filter(employee__company_id=dept)

        yb_result_count = 0
        for i in yb_obj:
            Record_all = i.topicsauditrecord_set.all()
            for Record in Record_all:
                if Record.node == "result":
                    yb_result_count += 1

        db_obj = Topics.objects.filter(~Q(state__in=['cg', 'cancel', 'recall']), type="db", create_time__year=year)
        db_wj_obj = db_obj.filter(state="done")
        if month and month != '请选择月份':
            db_obj = db_obj.filter(create_time__month=month)
        if dept and dept != '请选择部门':
            db_obj = db_obj.filter(employee__company_id=dept)
        db_result_count = 0
        for i in db_obj:
            db_Record_all = i.topicsauditrecord_set.all()
            for db_Record in db_Record_all:
                if db_Record.node == "result":
                    db_result_count += 1
        xz_obj = Topics.objects.filter(~Q(state__in=['cg', 'cancel', 'recall']), type="xz", create_time__year=year)
        xz_wj_obj = xz_obj.filter(state="done")
        if month and month != '请选择月份':
            xz_obj = xz_obj.filter(create_time__month=month)
        if dept and dept != '请选择部门':
            xz_obj = xz_obj.filter(employee__company_id=dept)
        xz_result_count = 0
        for i in xz_obj:
            if i.is_meeting == "b":
                xz_result_count += 1

        total_number = yb_obj.count() + db_obj.count() + xz_obj.count()
        total_wj_number = yb_wj_obj.count() + db_wj_obj.count() + xz_wj_obj.count()
        if total_number == 0:
            total_completion_rate = 0.00
            total_proportion = {"yb_total_proportion": 0.00, "db_total_proportion": 0.00, "xz_total_proportion": 0.00}
        else:
            total_completion_rate = round((total_wj_number / total_number)*100, 2)
            total_proportion = {"yb_total_proportion": round((yb_obj.count()/total_number)*100, 2), "db_total_proportion": round((db_obj.count()/total_number)*100, 2), "xz_total_proportion": round((xz_obj.count()/total_number)*100, 2)}

        yf_list, data_list, fl_data, dep_list, dep_number_list, year_list, dep_dict_list = select_echarts_data().select_yf_data(year=year, month=month, dept=dept)

        if dept and dept != '请选择部门':
            com = Company.objects.get(id=dept)
            dept_name = com.name
        else:
            dept_name = '请选择部门'
        context = {'realname': real_name, 'position': position, 'department': department,
                   "yb_count": yb_obj.count(),
                   "yb_completion_rate": round(yb_wj_obj.count() / yb_obj.count() * 100, 2) if yb_obj.count() > 0 else 0,
                   "db_count": db_obj.count(),
                   "db_completion_rate": round(db_wj_obj.count() / db_obj.count() * 100, 2) if db_obj.count() > 0 else 0,
                   "xz_count": xz_obj.count(),
                   "xz_completion_rate": round(xz_wj_obj.count() / xz_obj.count() * 100, 2) if xz_obj.count() > 0 else 0,
                   "total_proportion": total_proportion, "total_number": total_number,
                   "total_completion_rate": total_completion_rate,
                   "yf_list": yf_list, "data_list": data_list, "fl_data": fl_data, "dep_list": dep_list,
                   "dep_number_list": dep_number_list, "year_list": year_list, "dep_dict_list": dep_dict_list,
                   "year_num": year, "month": month, "dept_id": dept, "dept": dept_name}
        return render(request, 'personnel/issue_statement.html', context)

class IssueDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        context = {'realname': real_name, 'position': position, 'department': department}
        return render(request, 'personnel/issue_detail.html', context)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        topic_type = request.POST.get('topic_type', '')
        year_choose = request.POST.get('year_choose', '')
        mouth_choose = request.POST.get('mouth_choose', '')
        search_data = request.POST.get('search_data', '')
        if mouth_choose:
            objs = Topics.objects.filter(Q(number__contains=search_data) | Q(topics_name__contains=search_data) | Q(nrwb__contains=search_data) | Q(zcwb__contains=search_data) | Q(fawb__contains=search_data) | Q(db_nrwb__contains=search_data) | Q(db_zcwb__contains=search_data) | Q(db_fawb__contains=search_data) | Q(employee__real_name__contains=search_data) | Q(employee__company__name__contains=search_data), state="done", type__contains=topic_type, iss_year__contains=year_choose, create_time__month=mouth_choose).order_by('-create_time')
        else:
            objs = Topics.objects.filter(Q(number__contains=search_data) | Q(topics_name__contains=search_data) | Q(nrwb__contains=search_data) | Q(zcwb__contains=search_data) | Q(fawb__contains=search_data) | Q(db_nrwb__contains=search_data) | Q(db_zcwb__contains=search_data) | Q(db_fawb__contains=search_data) | Q(employee__real_name__contains=search_data) | Q(employee__company__name__contains=search_data), state="done", type__contains=topic_type, iss_year__contains=year_choose).order_by('-create_time')

        data_list = [
            {'id': obj.id,
             'company': obj.employee.company.name,
             'apply_user': obj.employee.real_name,
             'number': obj.number,
             'state': obj.get_state_str(),
             'create_time': obj.create_time.strftime("%Y-%m-%d %H:%M"),
             'topics_name': obj.topics_name,
             'topics_estimate': obj.topics_estimate,
             'ysje': obj.ysje,
             'jfly': obj.jfly,
             'help_department': ", ".join([i.name for i in obj.help_department.all()]),
             "url": "/personal-center/SubjectDetailst.html?views=1&id=" + str(obj.id)} for obj in
            objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class VehicleReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        fl_data, hyl_count, hdc_count, lwj_count, mz_count, dep_list, dep_number_list = select_echarts_data().car_data("", "")
        return render(request, 'personnel/VehicleReport.html', {'realname': real_name, 'position': position, 'department': department, "fl_data": fl_data, "hyl_count": hyl_count,
                                                                "hdc_count": hdc_count, "lwj_count": lwj_count, "mz_count": mz_count, "dep_list": dep_list, "dep_number_list": dep_number_list})

    def post(self, request):
        start_time = request.POST.get("start_time", '')
        end_time = request.POST.get("end_time", '')
        print(start_time, end_time)
        fl_data, hyl_count, hdc_count, lwj_count, mz_count, dep_list, dep_number_list = select_echarts_data().car_data(start_time, end_time)
        returnDict = {'code': 200, 'message': '保存到数据库出错', 'data': {"fl_data": fl_data, "hyl_count": hyl_count, "hdc_count": hdc_count, "lwj_count": lwj_count, "mz_count": mz_count, "dep_list": dep_list, "dep_number_list": dep_number_list}}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class attendance(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        now = datetime.now()
        year = now.year
        month = now.month
        days = now.day

        if days < 25:
            month -= 1
        approve_flag, disp_flag = True, True
        # DancObj = request.user.checkworkattendance_set.filter(attendance__work_month=str(month), attendance__work_yesr=str(year), attendance__WorkType='1').order_by("-create_time")
        DancObj = CheckWorkTable.objects.filter(current_audit_users=request.user, WorkType='1')
        DispatchObj = CheckWorkTable.objects.filter(Q(current_audit_users=request.user) | Q(apply_user=request.user), WorkType='2').order_by("-create_time")
        if not DancObj:
            if month == 1 and days <= 10:
                month = 12
                year = year - 1
            approve_flag = False
            print(month, year)
            DancObj = request.user.checkworkattendance_set.filter(attendance__work_month=str(month), attendance__work_yesr=str(year), attendance__WorkType='1').order_by("-create_time")
        if not DispatchObj:
            disp_flag = False
            DispatchObj = CheckWorkTable.objects.filter(audit_users_already=request.user, WorkType='2').order_by("-create_time")

        check_month = request.user.checkworkattendance_set.all().values("attendance__work_month").distinct()
        check_yesr = request.user.checkworkattendance_set.all().values("attendance__work_yesr").distinct()
        month_list, year_list = [], []

        for tt in check_month:
            month_list.append({'value': tt['attendance__work_month'], 'name': tt['attendance__work_month'] + "月"})

        for jj in check_yesr:
            year_list.append({'value': jj['attendance__work_yesr'], 'name': jj['attendance__work_yesr'] + "年"})

        xianshi_flag = 'false'

        yes_ont = request.user.checkworkattendance_set.all()
        if yes_ont:
            whether_verify = yes_ont.last().attendance.whether_verify          # 是否核对
            if whether_verify == '1':
                if days >= 25 or days <= 10:
                    xianshi_flag = 'true'
            else:
                tijiao_people = yes_ont.last().attendance.apply_user
                if tijiao_people == request.user:
                    xianshi_flag = 'true'
        else:
            xianshi_flag = 'true'

        first_obj, gauge_outfit, obj, audit_dic, is_audit = '', '', '', {}, "false"
        if DancObj:
            if approve_flag:
                obj = DancObj.first()
            else:
                obj = DancObj.first().attendance
            for audit_obj in obj.checkworkrecord_set.all().order_by("update_time"):
                audit_dic[audit_obj.node] = {'state': audit_obj.state, 'node': audit_obj.node,
                'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}

            first_obj = obj.checkworkattendance_set.filter(attendance=obj)
            gauge_outfit = obj.gauge_outfit
            if obj.current_audit_users.all().count():
                if request.user in obj.current_audit_users.all():
                    is_audit = "true"

        is_audit_disp = 'false'
        if DispatchObj and disp_flag:
            if request.user in DispatchObj.first().current_audit_users.all():
                is_audit_disp = 'true'

        DispatchDataObj, DispatchTitle, Dispatch_audit_dic, DisObj = '', "", {}, ""
        if DispatchObj:
            DispatchTitle = DispatchObj.first().gauge_outfit
            DisObj = DispatchObj.first()
            DispatchDataObj = CheckWorkLaborDispatch.objects.filter(attendance=DispatchObj.first())

            for AuditObj in DispatchObj.first().checkworkrecord_set.all().order_by("update_time"):
                Dispatch_audit_dic[AuditObj.node] = {'state': AuditObj.state, 'node': AuditObj.node,
                'signature_picture': '/media/' + str(AuditObj.audit_people.signature_picture) if (AuditObj.audit_people.signature_picture and AuditObj.state != 'unaudit') else ''}

        DispatchMoth = request.user.checkworktable_set.filter(WorkType='2').values("work_month").distinct()
        DispatchYear = request.user.checkworktable_set.filter(WorkType='2').values("work_yesr").distinct()
        dispat_month_list, dispat_year_list = [], []
        for ii in DispatchMoth:
            dispat_month_list.append({'value': ii['work_month'], 'name': ii['work_month'] + "月"})

        for kk in DispatchYear:
            dispat_year_list.append({'value': kk['work_yesr'], 'name': kk['work_yesr'] + "年"})

        returnDict = {'realname': real_name, 'position': position, 'department': department, "obj": first_obj, "gauge_outfit": gauge_outfit, "CheckObj": obj,
                      "create_time": obj.create_time.strftime("%Y年%m月%d日") if obj else "", "audit_dic": audit_dic, "is_audit": is_audit, "month_list": month_list, "xianshi_flag": xianshi_flag, "year_list": year_list, "DispatchTitle": DispatchTitle, "DispatchDataObj": DispatchDataObj,
                      "DispatchCreate": DispatchObj.first().create_time.strftime("%Y年%m月%d日") if DispatchTitle else "", "Dispatch_audit_dic": Dispatch_audit_dic, "dispat_month_list": dispat_month_list, "dispat_year_list": dispat_year_list, "is_audit_disp": is_audit_disp, "DisObj": DisObj}
        return render(request, 'personnel/attendance.html', returnDict)

class AttendanceStatistics(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        now = datetime.now()
        year = now.year
        month = now.month
        days = now.day
        if days < 25:
            if month == 1:
                month = 12
                start_time = f"{year - 1}-12-25"
                end_time = f"{year}-{month}-10"
                year = year - 1
            else:
                start_time = f"{year}-{month - 1}-25"
                end_time = f"{year}-{month}-10"
                month = month - 1
        else:
            start_time = f"{year}-{month}-25"
            # end_time = f"{year}-{month}-{days+1}"
            current_date = date.today()
            end_time = current_date + timedelta(days=1)

        # =========================================================== 部门-劳务-是否审核 ===========================================================
        is_audit, audit_dic = "false", {}
        if CheckWorkTable.objects.filter(whether_verify="0", WorkType='1').count():
            is_audit = "true"

        is_dispatch_audit, dispatch_dic = "false", {}
        if CheckWorkTable.objects.filter(whether_verify="0", WorkType='2').count():
            is_dispatch_audit = "true"

        # =========================================================== 部门考勤-搜索月份-年份-科室 ====================================================
        month_list, year_list, dep_dict_list = [], [], []
        check_month = CheckWorkTable.objects.filter(state__in=['two', 'end'], WorkType='1').values("work_month").distinct()
        for months in check_month:
            month_list.insert(0, {'value': months['work_month'], 'name': months['work_month']+"月"})

        check_year = CheckWorkTable.objects.filter(state__in=['two', 'end'], WorkType='1').values("work_yesr").distinct()
        for years in check_year:
            year_list.insert(0, {'value': years['work_yesr'], 'name': years['work_yesr']+"年"})

        check_department = CheckWorkAttendance.objects.filter(attendance__WorkType='1', attendance__state__in=['two', 'end']).values("department").distinct()
        for department in check_department:
            dep_dict_list.insert(0, {'value': department['department'], 'name': department['department']})

        # =========================================================== 劳务派遣-搜索月份-年份 ========================================================
        dispatch_month_list, dispatch_year_list, dispatch_dep_dict_list = [], [], []
        dispatch_month = CheckWorkTable.objects.filter(state__in=['two', 'end'], WorkType='2').values("work_month").distinct()
        for aa in dispatch_month:
            dispatch_month_list.insert(0, {'value': aa['work_month'], 'name': aa['work_month'] + "月"})

        dispatch_yesr = CheckWorkTable.objects.filter(state__in=['two', 'end'], WorkType='2').values("work_yesr").distinct()
        for ss in dispatch_yesr:
            dispatch_year_list.insert(0, {'value': ss['work_yesr'], 'name': ss['work_yesr'] + "年"})

        dispatch_department = CheckWorkLaborDispatch.objects.filter(attendance__WorkType='2', attendance__state__in=['two', 'end']).values("department").distinct()
        for dep in dispatch_department:
            dispatch_dep_dict_list.insert(0, {'value': dep['department'], 'name': dep['department']})

        # =========================================================== 部门考勤-考勤汇总数据 ===========================================================
        gauge_outfit = f"{year}年{month}月份考勤"
        AttendanceObj = CheckWorkAttendance.objects.filter(attendance__WorkType='1', attendance__state__in=['two', 'end'], create_time__range=[start_time, end_time])

        # =========================================================== 劳务派遣-考勤汇总数据 ===========================================================
        DispatchTitle = f"{year}年{month}月京山市人民医院劳务派遣人员考勤及月度考核汇总表"
        DispatchObj = CheckWorkLaborDispatch.objects.filter(attendance__WorkType='2', attendance__state__in=['two', 'end'], create_time__range=[start_time, end_time])

        # =========================================================== 部门考勤-科室审核情况 ===========================================================
        all_count = CheckWorkTable.objects.filter(WorkType='1', create_time__range=[start_time, end_time]).count()
        updata_count = CheckWorkTable.objects.filter(WorkType='1', state__in=['two', 'end'], create_time__range=[start_time, end_time]).count()

        # =========================================================== 部门考勤-科室审核情况 ===========================================================
        dispatch_all_count = CheckWorkTable.objects.filter(WorkType='2', create_time__range=[start_time, end_time]).count()
        dispatch_updata_count = CheckWorkTable.objects.filter(WorkType='2', state__in=['two', 'end'], create_time__range=[start_time, end_time]).count()

        if is_audit == "false":
            audit_dic["signature_picture"] = '/media/' + str(Company.objects.get(id=16).head_people.signature_picture)

        if is_dispatch_audit == "false":
            dispatch_dic["signature_picture"] = '/media/' + str(Company.objects.get(id=16).head_people.signature_picture)
        return render(request, 'personnel/AttendanceStatistics.html', {'realname': real_name, 'position': position, 'department': department, "month_list": month_list, "is_audit": is_audit,
        "year_list": year_list, "dep_dict_list": dep_dict_list, "AttendanceObj": AttendanceObj, "is_dispatch_audit": is_dispatch_audit, "DispatchObj": DispatchObj, "DispatchTitle": DispatchTitle,
        "gauge_outfit": gauge_outfit, "dispatch_month_list": dispatch_month_list, "dispatch_year_list": dispatch_year_list, "all_count": all_count, "updata_count": updata_count,
        "dispatch_dep_dict_list": dispatch_dep_dict_list, "dispatch_all_count": dispatch_all_count, "dispatch_updata_count": dispatch_updata_count, "audit_dic": audit_dic, "dispatch_dic": dispatch_dic})

class user_list(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        return render(request, "personnel/user_list.html", {'realname': real_name, 'position': position, 'department': department, "company_list": company_list, "roomName": request.user.job_number})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        delete_type = request.POST.get("delete_type", '')
        search_value = request.POST.get("search_value", "")
        if delete_type in ["0", "1"]:
            all_data = User.objects.filter(~Q(id__in=['2', '3']), Q(real_name__contains=search_value) | Q(department__contains=search_value), is_delete=int(delete_type)).all().order_by('id')
        else:
            all_data = User.objects.filter(~Q(id__in=['2', '3']), Q(real_name__contains=search_value) | Q(department__contains=search_value)).all().order_by('id')

        count_num = all_data.count()
        returnList, user_index = [], 0
        for dat in all_data[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            one_dict = {}
            freeze = "已冻结" if dat.is_delete == 1 else "正常"
            one_dict["id"] = dat.id
            one_dict["real_name"] = dat.real_name
            one_dict["job_number"] = dat.job_number
            one_dict["username"] = dat.username
            one_dict["mobile"] = dat.mobile
            one_dict["mailbox"] = dat.mailbox
            one_dict["department"] = dat.company.name if dat.company else dat.department
            one_dict["position"] = dat.post
            one_dict["gender"] = '男' if dat.gender == 'male' else '女'
            one_dict["education"] = dat.education
            one_dict["marital_status"] = '单身' if dat.marital_status == 'single' else '已婚'
            one_dict["political_outlook"] = dat.political_outlook
            one_dict["nation"] = dat.nation
            one_dict["ID_number"] = dat.ID_number
            one_dict["native_place"] = dat.native_place
            one_dict["major"] = dat.major
            one_dict["freeze"] = freeze
            one_dict["graduated_university"] = dat.graduated_university
            one_dict["home_address"] = dat.home_address
            one_dict["remarks"] = dat.remarks
            one_dict["personnel_category"] = dat.role
            one_dict["url"] = f'<a href="javascript:;" style="color: #8B8378;">冻结</a> | <a href="javascript:;" onclick="FreezePersonnel({dat.id}, \'{freeze}\', 0)" style="color: #7CFC00;">解冻</a>' if dat.is_delete == 1 else f'<a href="javascript:;" onclick="FreezePersonnel({dat.id}, \'{freeze}\', 1)" style="color: #FF3030;">冻结</a> | <a href="javascript:;" style="color: #8B8378;">解冻</a>'


            if dat.signature_picture:
                signature_picture_url = '/media/' + str(dat.signature_picture)
            else:
                signature_picture_url = ''
            if dat.enclosure:
                enclosure_url = '/media/' + str(dat.enclosure)
            else:
                enclosure_url = ''
            one_dict["signature_picture"] = signature_picture_url
            one_dict["enclosure"] = enclosure_url
            returnList.append(one_dict)
            user_index += 1

        return_dict = {
            'code': 200,
            'message': 'success',
            "data": returnList, "totals": count_num
        }
        return HttpResponse(json.dumps(return_dict), content_type="application/json")

class new_user(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        returndata = Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")
        company_list = []
        for c in returndata:
            one_dict = {"id": c.id, "name": c.name}
            company_list.append(one_dict)
        return render(request, "personnel/new_user.html", {'realname': real_name, 'position': position, 'department': department, "company_list": company_list})

    def post(self, request):
        real_name = request.POST.get('real_name') # 真实姓名
        username= request.POST.get('username') # 账户名
        password = request.POST.get('password') # 账号密码
        department = request.POST.get('department') # 部门
        gender = request.POST.get('gender') # 性别
        education = request.POST.get('education','') # 学历
        marital_status = request.POST.get('marital_status','') # 婚姻状态
        political_outlook = request.POST.get('political_outlook','') # 政治面貌
        nation = request.POST.get('nation','') # 民族
        ID_number = request.POST.get('ID_number','') # 身份证号
        native_place = request.POST.get('native_place','') # 籍贯
        major = request.POST.get('major','') # 专业
        graduated_university = request.POST.get('graduated_university','') # 毕业院校
        position = request.POST.get('position','') # 职位
        home_address = request.POST.get('home_address','') # 家庭住址
        mobile = request.POST.get('mobile','') # 手机号码
        mailbox = request.POST.get('mailbox','') # 邮箱
        remarks = request.POST.get('remarks','') # 备注
        signature_picture = request.POST.get('signature_picture') # 签名图片
        enclosure = request.FILES.get('enclosure') # 附件

        if not all([real_name,username,password,department,gender]):
            returnDict = {"code": 400, "message": "缺少必传参数"}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        # 2.username检验
        if not re.match(r'^[a-zA-Z0-9_-]{2,20}$', username):
            returnDict = {'code': 400, 'message': '账号格式有误,2至20位字母数字构成'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if not re.match(r'^[a-zA-Z0-9]{6,20}$', password):
            returnDict = {'code': 400, 'message': '密码格式有误,6至20位字母数字构成'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if ID_number:
            if len(ID_number) != 18 and len(ID_number) != 15:
                returnDict = {'code': 400, 'message': '身份证长度有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mailbox:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', mailbox):
                returnDict = {'code': 400, 'message': '邮箱格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            returnDict = {'code': 400, 'message': '访问数据库失败','data':str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        if count > 0:
            try:
                del_count = User.objects.filter(username=username,is_delete=1).count()
            except Exception as e:
                returnDict = {'code': 400, 'message': '访问数据库失败', 'data': str(e)}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")
            if del_count >0:
                try:
                    User.objects.filter(username=username).delete()
                except Exception as e:
                    returnDict = {'code': 400, 'message': '访问数据库失败', 'data': str(e)}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
            else:
                returnDict = {'code': 400, 'message': '该账号已经存在，不能重复注册'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if mobile:
            if not re.match(r'^1[3-9]\d{9}$', mobile):
                returnDict = {'code': 400, 'message': 'mobile格式有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if gender == '男':
            gender = 'male'
        elif gender == '女':
            gender = 'female'
        else:
            returnDict = {'code': 400, 'message': '性别有误'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if marital_status:
            if marital_status == '已婚':
                marital_status = 'married'
            elif marital_status == '未婚':
                marital_status = 'single'
            else:
                returnDict = {'code': 400, 'message': '婚姻状态有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        if political_outlook:
            if political_outlook not in ['群众','团员','党员']:
                returnDict = {'code': 400, 'message': '政治面貌有误'}
                return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            user = User.objects.create_user(username=username,
                                            job_number=username,
                                            real_name=real_name,
                                            password=password,
                                            mobile=mobile,
                                            department=department.split("(")[0],
                                            gender=gender,
                                            education=education,
                                            marital_status=marital_status,
                                            nation=nation,
                                            political_outlook=political_outlook,
                                            ID_number=ID_number,
                                            native_place=native_place,
                                            major=major,
                                            graduated_university=graduated_university,
                                            position=position,
                                            home_address=home_address,
                                            mailbox=mailbox,
                                            remarks=remarks,
                                            enclosure=enclosure,
                                            signature_picture=signature_picture,
                                            group_id='6',
                                            company_id=department.split("(")[1].replace(")", "")
                                            )
        except Exception as e:
            returnDict = {'code': 400, 'message': '保存到数据库出错', 'data': str(e)}

            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        try:
            if signature_picture:
                user.signature_picture = signature_picture
                user.save()
        except Exception as e:
            returnDict = {'code': 400, 'message': '保存签名图片失败', 'data': str(e)}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")

        returnDict = {'code': 200, 'message': 'success'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SchedulingListView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        search_value = request.GET.get("search_value", None)
        if search_value:
            objs = Scheduling.objects.all().order_by('-create_time')
        else:
            objs = Scheduling.objects.all().order_by('-create_time')

        paginator = Paginator(objs, 20)
        currentPage = int(request.GET.get("page", 1))

        if paginator.num_pages > 15:
            if currentPage - 5 < 1:
                pageRange = range(1, 11)
            elif currentPage + 5 > paginator.num_pages:
                pageRange = range(currentPage - 5, paginator.num_pages + 1)
            else:
                pageRange = range(currentPage - 5, currentPage + 5)
        else:
            pageRange = paginator.page_range

        try:
            objs_list = paginator.page(currentPage)
        except PageNotAnInteger:
            objs_list = paginator.page(1)
        except:
            objs_list = paginator.page(paginator.num_pages)

        context = {'objs': objs_list, 'realname': real_name, 'position': position, 'department': department,
                   "paginator": paginator,
                   "page_range": pageRange,  # 此处自定义一个分页段
                   "currentPage": currentPage, "search_value": search_value}
        if not search_value:
            context.pop("search_value")
        # 改为值班人员展示列表
        return render(request, "personnel/stuff_shift_arrangement.html", context)

class SchedulingView(View):
    def get(self, request):
        context = {'realname': request.user.real_name, 'position': request.user.post,
                   }
        # 改为创建页面
        return render(request, 'personnel/set_scheduling.html', context)

    def post(self, request):
        job_number = request.POST.get('duty_list', None)  # 工号列表 例：["8166", "0000"]
        duty_Shift = request.POST.get('duty_Shift', None)                # 班次： 一线班，1；二线班，2

        for i in json.loads(job_number):
            user = User.objects.get(job_number=i)
            Scheduling.objects.create(user=user, day_type='b', type=duty_Shift, is_work=False, date=datetime.now())
        returnDict = {'code': 200, 'message': '创建成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class SchedulingDeleteView(View):
    def post(self, request):
        id = request.POST.get('id', None)
        obj = Scheduling.objects.get(id=id)
        sort_objs = SortLine.objects.filter(date__gte=datetime.now().strftime("%Y-%m-%d"), user=obj.user)
        if len(sort_objs) > 0:
            returnDict = {'code': 500, 'message': '删除失败！该员工已经安排后续值班，不能删除。'}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        obj.delete()
        returnDict = {'code': 200, 'message': '删除成功'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class roster_setting(View):
    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", "")
        line_type = request.POST.get("line_type", "")
        if line_type:
            line_obj = Scheduling.objects.filter(Q(user__real_name__contains=search_value), type=line_type)
        else:
            line_obj = Scheduling.objects.filter(user__real_name__contains=search_value)

        one_line_list, two_line_list = [], []
        for i in line_obj[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if i.type == "1":
                one_line_list.append({"Shift": "一线班", "name": i.user.real_name, "last_date": str(i.last_date).split(' ')[0], "shift_arrangement": "白班" if i.day_type=="a" else "晚班", "id": i.id})
            else:
                two_line_list.append({"Shift": "二线班", "name": i.user.real_name, "last_date": str(i.last_date).split(' ')[0], "shift_arrangement": "晚班", "id": i.id})

        roster_list = one_line_list + two_line_list
        returnDict = {'code': 200, 'message': 'ok', "data": roster_list, "totals": line_obj.count()}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class system_scheduling(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "personnel/system_scheduling.html", {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4()})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        names = request.POST.get("names", "")           # 值班人姓名
        dech_time = request.POST.get("dech_time", "")           # 值班时间
        duty_Shift = request.POST.get("duty_Shift", '')         # 班次
        start_year, start_month, start_day = "", "", ""
        end_year, end_month, end_day = "", "", ""
        if dech_time:
            start_t = dech_time.split("至")[0]
            start_year, start_month, start_day = int(start_t.split("-")[0]), int(start_t.split("-")[1]), int(start_t.split("-")[2])
            end_t = dech_time.split("至")[1]
            end_year, end_month, end_day = int(end_t.split("-")[0]), int(end_t.split("-")[1]), int(end_t.split("-")[2])

        if duty_Shift and dech_time and names:
            all_sched = SortLine.objects.filter(Q(user_id__real_name__contains=names), Q(type=int(duty_Shift)), date__gte=date(start_year, start_month, start_day), date__lte=date(end_year, end_month, end_day)).order_by("-id")
        elif duty_Shift and dech_time:
            all_sched = SortLine.objects.filter(Q(type=int(duty_Shift)), date__gte=date(start_year, start_month, start_day), date__lte=date(end_year, end_month, end_day)).order_by("-id")
        elif duty_Shift and names:
            all_sched = SortLine.objects.filter(Q(user_id__real_name__contains=names), Q(type=int(duty_Shift))).order_by("-id")
        elif dech_time and names:
            all_sched = SortLine.objects.filter(Q(user_id__real_name__contains=names), date__gte=date(start_year, start_month, start_day), date__lte=date(end_year, end_month, end_day)).order_by("-id")
        elif duty_Shift:
            all_sched = SortLine.objects.filter(type=int(duty_Shift)).order_by("-id")
        elif dech_time:
            all_sched = SortLine.objects.filter(date__gte=date(start_year, start_month, start_day), date__lte=date(end_year, end_month, end_day)).order_by("-id")
        elif names:
            all_sched = SortLine.objects.filter(user_id__real_name__contains=names).order_by("-id")
        else:
            all_sched = SortLine.objects.all().order_by("-id")

        sched_list = []
        for i in all_sched[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            sched_list.append({
                "Shift": "一线班" if i.type == "1" else "二线班",
                "name": i.user.real_name+"("+i.user.mobile+")" if i.type == "1" else i.user.real_name,
                "duty_time": i.date.strftime("%Y-%m-%d"),
                "shift_arrangement": "白班" if i.day_type == "a" else "夜班",
                "url": f"<a href='javascript:;' id={i.id} onclick='change_person_data(this.id)' style='color:red;'>修改</a>",
            })

        returnDict = {'code': 200, 'message': 'ok', "data": sched_list, "totals": all_sched.count()}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ManualShiftArrangement(View):
    def post(self, request):
        dech_start_time = request.POST.get("dech_start_time", None)
        Scheduling_Procedure(dech_start_time).main()
        returnDict = {'code': 200, 'message': 'ok'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class TimeSetting(View):
    def post(self, request):
        AdministrativeWorkTime = request.POST.get("AdministrativeWorkTime", None)              # 行政上班时间
        AdministrativeOffTime = request.POST.get("AdministrativeOffTime", None)                # 行政下班时间
        ClinicalWorkTime = request.POST.get("ClinicalWorkTime", None)                          # 临床上班时间
        ClinicalOffTime = request.POST.get("ClinicalOffTime", None)                            # 临床下班班时间

        if AdministrativeWorkTime or AdministrativeOffTime:
            try:
                duty_obj = DutyTime.objects.get(type="xz")
                if AdministrativeWorkTime:
                    duty_obj.work_time = AdministrativeWorkTime
                if AdministrativeOffTime:
                    duty_obj.off_time = AdministrativeOffTime
                duty_obj.save()
            except:
                DutyTime.objects.create(
                    type="xz",
                    work_time=AdministrativeWorkTime,
                    off_time=AdministrativeOffTime,
                    create_people=request.user
                )
        if ClinicalWorkTime or ClinicalOffTime:
            try:
                duty_obj = DutyTime.objects.get(type="lc")
                if ClinicalWorkTime:
                    duty_obj.work_time = ClinicalWorkTime
                if ClinicalOffTime:
                    duty_obj.off_time = ClinicalOffTime
                duty_obj.save()
            except:
                DutyTime.objects.create(
                    type="lc",
                    work_time=ClinicalWorkTime,
                    off_time=ClinicalOffTime,
                    create_people=request.user
                )

        returnDict = {'code': 200, 'message': 'ok'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class UploadExcel(View):
    def post(self, request):
        xls_file = request.FILES.get('file1')
        fj_number = request.POST.get('fj_number', '')
        # print("++++++++++++++++++++++++: ", xls_file, fj_number)
        first_line_li = []  # 一线班列表
        second_line_li = []  # 二线班列表
        curr_year = re.findall("（(.*?)年", xls_file.name, re.S)
        now = datetime.now()
        Y = now.year
        M = now.month
        D = now.day
        if curr_year:
            curr_year = curr_year[0]
        else:
            if M == 12:
                curr_year = Y + 1
            else:
                curr_year = Y
        if xls_file:
            workbook = xlrd.open_workbook(file_contents=xls_file.read())
            worksheet = workbook.sheet_by_index(0)
            for row_index in range(1, worksheet.nrows):
                row_data = worksheet.row_values(row_index)
                if row_data[0] != "":
                    print("row_data: ", )
                    # data = date.fromordinal(datetime(1900, 1, 1).toordinal() + int(row_data[0]) - 2)
                    formatted_date = datetime.strptime(str(curr_year) + "-" + row_data[0].split("（")[0].replace("月", "-").replace("日", ""), "%Y-%m-%d").strftime('%Y-%m-%d')  # 值班时间
                else:
                    formatted_date = ""
                if row_data[-1] != "":
                    try:
                        user_obj = User.objects.get(job_number=str(int(float(row_data[-1]))))
                        new_string = re.sub(r'\s+', '', row_data[-2])
                        if user_obj.real_name != new_string:
                            returnDict = {"code": 401,
                                          'message': f'工号为：{str(int(float(row_data[-1])))}对应的人员与{new_string}不匹配，请检查表格数据是否无误！'}
                            return HttpResponse(json.dumps(returnDict), content_type="application/json")
                        second_line_li.append({"date": formatted_date, "type": "2", "day_type": "b", "user": user_obj})
                    except:
                        returnDict = {'code': 400,
                                      'message': f'导入Excel表格失败！未找到工号为：{str(int(float(row_data[3])))}的人员信息！'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                try:
                    user_obj = User.objects.get(job_number=str(int(float(row_data[3]))))
                    new_string = re.sub(r'\s+', '', row_data[2])
                    if user_obj.real_name != new_string.replace(''.join(re.findall("\d", new_string)), ''):
                        returnDict = {"code": 401, 'message': f'工号为：{str(int(float(row_data[3])))}对应的人员与{new_string}不匹配，请检查表格数据是否无误！'}
                        return HttpResponse(json.dumps(returnDict), content_type="application/json")
                    first_line_li.append(
                        {"date": formatted_date, "type": "1", "day_type": "a" if row_data[1] == "白班" else "b",
                         "user": user_obj, "tel_num": user_obj.mobile})
                except:
                    returnDict = {'code': 400, 'message': f'导入Excel表格失败！未找到工号为：{str(int(float(row_data[3])))}的人员信息！'}
                    return HttpResponse(json.dumps(returnDict), content_type="application/json")
        meseage_tel_li, job_num_list = [], []

        for i in range(len(first_line_li)):
            if first_line_li[i]['date'] == "":
                first_line_li[i]['date'] = first_line_li[i - 1]['date']
            meseage_tel_li.append(first_line_li[i]['tel_num'])  # 获取需要发送短信的电话
            if first_line_li[i]['user'].job_number not in job_num_list:
                job_num_list.append(first_line_li[i]['user'].job_number)
            SortLine.objects.create(date=first_line_li[i]['date'], type=first_line_li[i]['type'],
                                    day_type=first_line_li[i]['day_type'], user=first_line_li[i]['user'])

        for j in range(len(second_line_li)):
            if second_line_li[j]['user'].job_number not in job_num_list:
                job_num_list.append(second_line_li[j]['user'].job_number)
            SortLine.objects.create(date=second_line_li[j]['date'], type=second_line_li[j]['type'],
                                    day_type=second_line_li[j]['day_type'], user=second_line_li[j]['user'])
        next_month = now.month + 1
        if next_month == 13:  # 如果下个月是 13，即为明年 1 月
            next_month = 1
        serial_content = f"总值班：{next_month}月份总值班排班已发至您OA邮箱，请查收。"

        res = send_mssage(list(set(meseage_tel_li)), serial_content)                      # 发送短信

        file_name = f"{next_month}月份总值班排班"

        time_str = f"{Y} 年 {M} 月 {D} 日"
        message_content = f'<p></br></p><p><br/></p><p>总值班：{file_name}</p><p><br/></p><p><br/></p><p><br/></p><p>&nbsp; &nbsp; &nbsp; &nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;' \
                          f'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ' \
                          f'{time_str}</p><p><br style="white-space: normal;"/></p><p><br/></p>'


        InboxInfo_obj = InboxInfo.objects.create(
            content=message_content,
            plain_text=f'总值班：{next_month}月份总值班排班。  {time_str}',
            title=file_name,
            accessory_uuid=fj_number,
            is_draft=False,
            proposer=request.user
        )
        for i in job_num_list:
            user_obj = User.objects.get(job_number=i)
            InboxInfoPeople.objects.create(
                inbox_id=InboxInfo_obj,
                recipient=user_obj,
                recipient_name=f"{user_obj.real_name}<{user_obj.job_number}>"
            )
        returnDict = {'code': 200, 'message': '导入Excel表格成功！'}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ChangeScheduling(View):
    def post(self, request):
        id = request.POST.get("id", None)
        job_number = request.POST.get("job_number", None)
        obj = SortLine.objects.get(id=id)
        user_obj = User.objects.get(job_number=job_number)
        obj.user = user_obj
        obj.save()
        returnDict = {"code": 200, "message": "修改成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class QuerySummary(View):
    def post(self, request):
        year_val = request.POST.get("year_val", None)
        month_val = request.POST.get("month_val", None)
        dept_val = request.POST.get("dept_val", None)
        WorkType = request.POST.get("WorkType", None)
        dept_val = "" if dept_val == 'undefined' else dept_val

        AttendanceList = []
        if WorkType == '1':
            flag = 'true'
            if month_val and not year_val and not dept_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_month=month_val)
            elif month_val and year_val and not dept_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_month=month_val, attendance__work_yesr=year_val)
            elif month_val and dept_val and not year_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_month=month_val, department=dept_val)
            elif year_val and not month_val and not dept_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_yesr=year_val)
            elif year_val and dept_val and not month_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], attendance__work_yesr=year_val, department=dept_val)
            elif dept_val and not month_val and not year_val:
                check_obj = CheckWorkAttendance.objects.filter(attendance__state__in=["two", "end"], department=dept_val)
            else:
                check_obj = CheckWorkAttendance.objects.filter(attendance__work_month=month_val, attendance__work_yesr=year_val, department=dept_val)

            if check_obj:
                create_time = check_obj.first().create_time.strftime("%Y年%m月%d日")
            else:
                create_time = ""

            gauge_outfit = f"{year_val}年{month_val}月份考勤"
            for i in check_obj:
                AttendanceList.append({
                    "serial": i.serial, "department": i.department, "job_number": i.job_number, "practice": i.practice,
                    "name": i.name, "attendance_days": i.attendance_days, "work_days": i.work_days,
                    "aid_jing": i.aid_jing, "quarantine": i.quarantine, "heterodyne": i.heterodyne,
                    "education": i.education, "planning": i.planning, "maternity": i.maternity, "annual": i.annual,
                    "absence": i.absence, "sick": i.sick, "industrial": i.industrial,
                    "visit": i.visit, "marriage": i.marriage, "bereavement": i.bereavement, "vacation": i.vacation,
                    "parental_leave": i.parental_leave, "notes": i.notes
                })
            audit_dic = []
            if check_obj:
                RecordObj = CheckWorkRecord.objects.filter(~Q(state='unaudit'), parent_id=check_obj.first().attendance, node="one")
                if RecordObj.count():
                    audit_dic.append({"real_name": RecordObj.first().audit_people.real_name, "signature_picture":
                        ('/media/' + str(RecordObj.first().audit_people.signature_picture)) if RecordObj.first().audit_people.signature_picture else ""})

        else:
            flag, create_time, audit_dic = 'false', "", []
            if month_val and not year_val:
                check_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], work_month=month_val)
            elif year_val and not month_val:
                check_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], work_yesr=year_val)
            else:
                check_obj = CheckWorkTable.objects.filter(state__in=["two", "end"], work_month=month_val, work_yesr=year_val, WorkType='2')
            attendance_list = []
            for i in check_obj:
                attendance_list.append(i.id)

            if check_obj:
                if check_obj.first().whether_verify == '1':
                    rsk_obj = Company.objects.get(id=16).head_people
                    audit_dic.append({'state': 'audit', 'node': '', 'signature_picture': ('/media/' + str(rsk_obj.signature_picture)) if rsk_obj.signature_picture else ''})

            check_obj = CheckWorkLaborDispatch.objects.filter(attendance__in=attendance_list)
            gauge_outfit = f"{year_val}年{month_val}月京山市人民医院劳务派遣人员考勤及月度考核汇总表"
            for i in check_obj:
                AttendanceList.append({
                    "serial": i.serial, "department": i.department, "project_name": i.project_name, "attendance_days": i.attendance_days,
                    "leave_type": i.leave_type, "labor_discipline": i.labor_discipline, "work_quality": i.work_quality,
                    "working_ability": i.working_ability, "other": i.other, "total_score": i.total_score, "notes": i.notes
                })

        returnDict = {"code": 200, "message": "查询成功！", "AttendanceObj": AttendanceList, "gauge_outfit": gauge_outfit, "flag": flag, "company_name": dept_val, "create_time": create_time, "audit_dic": audit_dic, "WorkType": WorkType}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class month_summary(View):
    def post(self, request):
        year_val = request.POST.get("year_val", None)
        month_val = request.POST.get("month_val", None)
        types = request.POST.get("types", None)


        if types == '1':
            gauge_outfit = f"{year_val}年{month_val}月份考勤"
            check_obj = request.user.checkworkattendance_set.filter(attendance__work_month=month_val, attendance__work_yesr=year_val, attendance__WorkType='1')
            company_name = check_obj.first().attendance.company.name
            create_time = check_obj.first().attendance.create_time.strftime("%Y年%m月%d日")
            audit_dic, AttendanceList = {}, []
            for audit_obj in check_obj.first().attendance.checkworkrecord_set.all().order_by("update_time"):
                audit_dic[audit_obj.node] = {'state': audit_obj.state, 'node': audit_obj.node, 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}
            for i in check_obj.first().attendance.checkworkattendance_set.all():
                AttendanceList.append({
                    "serial": i.serial, "department": i.department, "job_number": i.job_number, "practice": i.practice, "name": i.name, "attendance_days": i.attendance_days, "work_days": i.work_days,
                    "aid_jing": i.aid_jing, "quarantine": i.quarantine, "heterodyne": i.heterodyne, "education": i.education, "planning": i.planning, "maternity": i.maternity, "annual": i.annual,
                    "absence": i.absence, "sick": i.sick, "industrial": i.industrial, "visit": i.visit, "marriage": i.marriage, "bereavement": i.bereavement, "vacation": i.vacation,
                    "parental_leave": i.parental_leave, "notes": i.notes
                })

        else:
            gauge_outfit = f"京山市人民医院劳务派遣人员考勤及月度考核汇总表"
            check_obj = request.user.checkworktable_set.filter(work_month=month_val, work_yesr=year_val, WorkType='2')
            company_name = check_obj.first().company.name if check_obj else ""
            create_time = check_obj.first().create_time.strftime("%Y年%m月%d日") if check_obj else ""
            audit_dic, AttendanceList = {}, []
            if check_obj:
                for audit_obj in check_obj.first().checkworkrecord_set.all().order_by("update_time"):
                    audit_dic[audit_obj.node] = {'state': audit_obj.state, 'node': audit_obj.node, 'signature_picture': '/media/' + str(audit_obj.audit_people.signature_picture) if (audit_obj.audit_people.signature_picture and audit_obj.state != 'unaudit') else ''}

                AttendanceObj = CheckWorkLaborDispatch.objects.filter(attendance=check_obj.first())
                for i in AttendanceObj:
                    AttendanceList.append({
                        "serial": i.serial, "project_name": i.project_name, "attendance_days": i.attendance_days, "leave_type": i.leave_type, "labor_discipline": i.labor_discipline,
                        "work_quality": i.work_quality, "working_ability": i.working_ability, "other": i.other, "total_score": i.total_score, "notes": i.notes
                    })

        returnDict = {"code": 200, "message": "查询成功！", "AttendanceObj": AttendanceList, "gauge_outfit": gauge_outfit, "company_name": company_name, "create_time": create_time, "audit_dic": audit_dic}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class ContractCountersigning(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")

        dept_id, dept = '请选择立项科室', '请选择立项科室'
        dep_dict_list = []
        all_com = Company.objects.all()
        for i in all_com:
            dep_dict_list.append({'value': i.id, 'name': i.name})

        return render(request, "personnel/contract_countersigning.html", {'realname': real_name, 'position': position, 'department': department, "uuid": uuid.uuid4(), "dept_id": dept_id, "dept": dept, "dep_dict_list": dep_dict_list})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)

        search_data = request.POST.get("search_data", '')
        search_dept = request.POST.get("search_dept", '')
        category = request.POST.get("category", '')

        select_sql = f"SELECT * FROM (SELECT A.id, A.create_time, B.real_name, C.`name`, A.contract_name, A.contract_number, CASE WHEN A.contract_type = '1' THEN '服务类' WHEN A.contract_type = '2' THEN '货物类' WHEN A.contract_type = '3' THEN '工程类' ELSE '其它类' END AS 'contract_type', D.`name` AS 'requirement_department', A.source, A.contract_amount, CONCAT( '/finance/business_contract_detail_view?id=', A.id ) AS url, A.fj_number, '0' as 'whether_upload' FROM `finance_businesscontract` A LEFT JOIN tb_users_message B ON A.apply_user_id = B.id LEFT JOIN administrative_company C ON A.company_id = C.id LEFT JOIN administrative_company D ON A.product_company_id = D.id WHERE A.state = 'seven' AND A.company_id LIKE '%{search_dept}%' AND `contract_name` LIKE '%{search_data}%' AND A.contract_type LIKE '%{category}%' UNION ALL SELECT Z.id, Z.create_time, Y.real_name, X.`name`, W.contract_name, W.contract_number, CASE WHEN W.contract_type = '1' THEN '服务类' WHEN W.contract_type = '2' THEN '货物类' WHEN W.contract_type = '3' THEN '工程类' ELSE '其它类' END AS 'contract_type', X.`name` AS 'requirement_department', CASE WHEN W.funding_source = '1' THEN '自有经费' WHEN W.funding_source = '2' THEN '学科经费' WHEN W.funding_source = '3' THEN '科研经费' WHEN W.funding_source = '4' THEN '财政拨款' WHEN W.funding_source = '5' THEN '贴息贷款' WHEN W.funding_source = '6' THEN '专项债券' WHEN W.funding_source = '6' THEN '工会经费' ELSE '' END AS 'source', W.ysje as contract_amount, CONCAT( '/finance/ContractDetail.html?id=', Z.id ) AS url, Z.fj_number, Z.whether_upload as 'whether_upload' FROM `administrative_contractapproval` Z LEFT JOIN tb_users_message Y ON Z.apply_user_id=Y.id LEFT JOIN administrative_company X ON Y.company_id=X.id LEFT JOIN administrative_topics W ON Z.topics_id_id=W.id WHERE Z.state='end' AND X.id LIKE '%{search_dept}%' AND `title` LIKE '%{search_data}%' AND W.contract_type LIKE '%{category}%') base ORDER BY create_time DESC"
        with connection.cursor() as cursor:
            cursor.execute(select_sql)
            objs = cursor.fetchall()
        data_list = []
        for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            if str(obj[1]) > '2024-06-01 00:00:00' and obj[12] == '0':
                flow_url = f"""<a href='/finance/ContractDetail.html?id={obj[0]}')>查看</a> | <a href='javascript:;' onclick="online_tag('{obj[4]}', '{obj[3]}', '{obj[8]}', '{obj[9]}', '{obj[11]}')")>上传合同</a>"""
            elif str(obj[1]) > '2024-06-01 00:00:00' and obj[12] == '1':
                flow_url = f"""<a href='/finance/ContractDetail.html?id={obj[0]}')>查看</a> | <a href='javascript:;' style="color: #CFCFCF;")>上传合同</a>"""
            else:
                flow_url = f"""<a class="plugin-action" href="{obj[10]}">查看</a>"""
            data_list.append({'id': obj[0], 'applicant': obj[2], 'ProjectDep': obj[3], "contract_name": obj[4], 'contract_number': obj[5],
                          'contract_type': obj[6], 'requirement': obj[7], 'source': obj[8], 'contract_money': obj[9], 'url': flow_url, "fj_number": obj[11]})
        returnDict = {'status': 'success', "totals": len(objs), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class search_dispatch_data(View):
    def post(self, request):
        year_val = request.POST.get("year_val", None)
        month_val = request.POST.get("month_val", None)
        dept_val = request.POST.get("dept_val", None)
        types = request.POST.get("type", None)
        gauge_outfit = f"{year_val}年{month_val}月京山市人民医院劳务派遣人员考勤及月度考核汇总表"
        AttendanceList, audit_dic = [], []
        flag = '0'
        if types == '2':
            check_obj = CheckWorkLaborDispatch.objects.filter(attendance__work_month=month_val, attendance__work_yesr=year_val, attendance__WorkType='2', department=dept_val)
            if check_obj and check_obj.first().attendance.state in ['two', 'end']:
                RecordObj = CheckWorkRecord.objects.filter(~Q(state='unaudit'), parent_id=check_obj.first().attendance, node="one")
                if RecordObj.count():
                    audit_dic.append({"real_name": RecordObj.first().audit_people.real_name, "signature_picture":
                        ('/media/' + str(RecordObj.first().audit_people.signature_picture)) if RecordObj.first().audit_people.signature_picture else ""})
        else:
            check_obj = CheckWorkLaborDispatch.objects.filter(attendance__work_month=month_val, attendance__work_yesr=year_val, attendance__WorkType='2')
            if check_obj and check_obj.first().attendance.whether_verify == '1':
                flag = '1'
                rsk_obj = Company.objects.get(id=16).head_people
                audit_dic.append({'state': 'audit', 'node': '', 'signature_picture': ('/media/' + str(rsk_obj.signature_picture)) if rsk_obj.signature_picture else ''})

        for i in check_obj:
            AttendanceList.append({
                "serial": i.serial, "department": i.department, "project_name": i.project_name, "attendance_days": i.attendance_days,
                "leave_type": i.leave_type, "labor_discipline": i.labor_discipline, "work_quality": i.work_quality,
                "working_ability": i.working_ability, "other": i.other, "total_score": i.total_score, "notes": i.notes
            })

        returnDict = {"code": 200, "message": "查询成功！", "AttendanceObj": AttendanceList, "gauge_outfit": gauge_outfit, "audit_dic": audit_dic, "flag": flag}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")



class freeze_personnel(View):
    def post(self, request):
        user_id = request.POST.get("id", None)
        operate_type = request.POST.get("operate_type", None)

        user_obj = User.objects.get(id=int(user_id))
        user_obj.is_delete = operate_type
        if int(operate_type) == 0:
            user_obj.last_login = datetime.now()
        user_obj.save()
        returnDict = {'status': 'success', "code": 200, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class batch_operation(View):
    def post(self, request):
        id_list = request.POST.get("id_list", None)
        bulk_type = request.POST.get("bulk_type", None)
        print(id_list)
        for ids in id_list.split(","):
            user_obj = User.objects.get(id=int(ids))
            user_obj.is_delete = bulk_type
            if int(bulk_type) == 0:
                user_obj.last_login = datetime.now()
            user_obj.save()
        returnDict = {'status': 'success', "code": 200, "message": "操作成功！"}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class VehicleReportDetail(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, "personnel/VehicleReportDetail.html", {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", "")
        start_time = request.POST.get("StartTime", "")
        end_time = request.POST.get("EndTime", "")
        if start_time and end_time:
            objs = VehicleApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(route__contains=search_value) | Q(travelers_numbers__contains=search_value) | Q(field_leader__contains=search_value)
                                         | Q(field_leader_numbers__contains=search_value) | Q(vehicles__contains=search_value) | Q(drivers__contains=search_value), state="cgb", start_time__gte=start_time, end_time__lte=end_time).order_by("-create_time")
        else:
            objs = VehicleApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(route__contains=search_value) | Q(travelers_numbers__contains=search_value) | Q(field_leader__contains=search_value)
                                         | Q(field_leader_numbers__contains=search_value) | Q(vehicles__contains=search_value) | Q(drivers__contains=search_value), state="cgb").order_by("-create_time")
        data_list = [
            {'id': obj.id, 'subject': f'<a href="/personal-center/Vehicle_apply_detail.html?id={obj.id}">{obj.subject}</a>',
             'route': obj.route, "apply_user": obj.apply_user.real_name, 'travelers_names': obj.field_leader,
             'use_car_start_time': obj.start_time.strftime("%Y.%m.%d %H:%M"), 'use_car_end_time': obj.end_time.strftime("%Y.%m.%d %H:%M"),
             'vehicles': obj.vehicles,
             'drivers': obj.drivers} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class ClickOnPreScheduling(View):
    def post(self, request):
        types = request.POST.get("type", "")
        development = 'production'
        SchedulingList = AutomaticScheduling(development, types).main_fun(request)
        if not SchedulingList:
            returnDict = {'status': 'success', "message": "已生成排班数据，无需再次排班！", "code": 400}
            return HttpResponse(json.dumps(returnDict), content_type="application/json")
        returnDict = {'status': 'success', "message": "操作成功！", "data": SchedulingList, "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class TravelReport(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        return render(request, 'personnel/TravelReport.html', {'realname': real_name, 'position': position, 'department': department})

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        search_value = request.POST.get("search_value", "")
        start_time = request.POST.get("StartTime", "")
        end_time = request.POST.get("EndTime", "")
        travel_type = request.POST.get("travel_type", "")
        if travel_type == "0" or not travel_type:
            if start_time and end_time:
                objs = TravelApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(subject__contains=search_value), state="five", start_time__gte=start_time, end_time__lte=end_time).order_by("-create_time")
            else:
                objs = TravelApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(subject__contains=search_value), state="five").order_by("-create_time")
        else:
            if start_time and end_time:
                objs = TravelApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(subject__contains=search_value), travel_type=travel_type, state="five", start_time__gte=start_time, end_time__lte=end_time).order_by("-create_time")
            else:
                objs = TravelApply.objects.filter(Q(apply_user__real_name__contains=search_value) | Q(subject__contains=search_value), travel_type=travel_type, state="five").order_by("-create_time")
        data_list = [
            {'id': obj.id, 'travel_people': ','.join([kk.real_name for kk in obj.travel_users.all()]),
             'company': obj.company.name,
             'apply_user': obj.apply_user.real_name,
             'travel_type': obj.get_travel_type_display(),
             'start_time': obj.start_time.split(" ")[0],
             'end_time': obj.end_time.split(" ")[0],
             'subject': obj.subject, 'note': obj.note,
             'route': obj.route} for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")

class CheckInStatisticsView(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
            position = request.user.post
            department = request.user.company.name
        except:
            return redirect("/")
        head_flag = "false"
        if request.user.group.id in [3, 4, 5, 7] or request.user == request.user.company.head_people:
            head_flag = "true"

        SchedulingObj = ThreePartyAttendanceInformation.objects.filter(job_number=request.user.job_number, duty_date=datetime.now().strftime("%Y-%m-%d"))
        morning_check_obj, morning_off_work_obj, afternoon_work_end_obj, evening_work_end_obj = '', '', '', ''
        if SchedulingObj.count():
            start_time = f'{datetime.now().strftime("%Y-%m-%d")} {SchedulingObj.first().start_time}:00'
            end_time = f'{datetime.now().strftime("%Y-%m-%d")} {SchedulingObj.first().end_time}:00'

            date_format = "%Y-%m-%d %H:%M:%S"
            morning_check_time_start = datetime.strptime(start_time, date_format) - timedelta(hours=1)
            morning_check_time_end = datetime.strptime(start_time, date_format) + timedelta(hours=0.5)
            morning_check_obj = CheckInInformation.objects.filter(check_time__range=[morning_check_time_start, morning_check_time_end], userCode=request.user.job_number)

            morning_off_work_time = datetime.strptime(end_time, date_format) + timedelta(hours=0.5)
            morning_off_work_obj = CheckInInformation.objects.filter(check_time__range=[morning_check_time_end, morning_off_work_time], userCode=request.user.job_number)

            if SchedulingObj.first().start_time1:
                try:
                    start_time1 = f'{datetime.now().strftime("%Y-%m-%d")} {SchedulingObj.first().start_time1}:00'
                    afternoon_work_end_time = datetime.strptime(start_time1, date_format) + timedelta(hours=0.5)
                    afternoon_work_end_obj = CheckInInformation.objects.filter(check_time__range=[morning_off_work_time, afternoon_work_end_time], userCode=request.user.job_number)

                    end_time1 = f'{datetime.now().strftime("%Y-%m-%d")} {SchedulingObj.first().end_time1}:00'
                    evening_work_end_time = datetime.strptime(end_time1, date_format) + timedelta(hours=2)
                    evening_work_end_obj = CheckInInformation.objects.filter(check_time__range=[afternoon_work_end_time, evening_work_end_time], userCode=request.user.job_number)
                except:
                    pass
        return render(request, 'personnel/CheckInStatistics.html', {'realname': real_name, 'position': position, 'department': department, 'SchedulingObj': SchedulingObj.first() if SchedulingObj else "",
                                                                    'morning_check_obj': morning_check_obj, "morning_off_work_obj": morning_off_work_obj, "afternoon_work_end_obj": afternoon_work_end_obj,
                                                                    'evening_work_end_obj': evening_work_end_obj, 'head_flag': head_flag})

    def post(self, request):
        search_year = request.POST.get("year", datetime.year)
        search_month = request.POST.get("month", datetime.month)
        search_day = request.POST.get("day", datetime.month)
        calendar_lines = create_calendar().get_calendar(int(search_year), int(search_month), int(search_day), request.user)
        returnDict = {'status': 'success', "message": "操作成功！", "data": calendar_lines, "code": 200}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class check_in_detail(View):
    def post(self, request):
        check_in_data = request.POST.get("check_in_data", '')
        SplitDate = check_in_data.split("-")
        check_year = SplitDate[0]
        check_month = SplitDate[1]
        check_day = SplitDate[2]
        if int(SplitDate[1]) < 10:
            check_month = f'0{SplitDate[1]}'
        if int(SplitDate[2]) < 10:
            check_day = f'0{SplitDate[2]}'
        duty_date = f"{check_year}-{check_month}-{check_day}"
        SchedulingObj = ThreePartyAttendanceInformation.objects.filter(job_number=request.user.job_number, duty_date=duty_date)
        morning_check_obj, morning_off_work_obj, afternoon_work_end_obj, evening_work_end_obj = '', '', '', ''
        if SchedulingObj.count():
            start_time = f'{duty_date} {SchedulingObj.first().start_time}:00'
            end_time = f'{duty_date} {SchedulingObj.first().end_time}:00'

            date_format = "%Y-%m-%d %H:%M:%S"
            morning_check_time_start = datetime.strptime(start_time, date_format) - timedelta(hours=1)
            morning_check_time_end = datetime.strptime(start_time, date_format) + timedelta(hours=0.5)
            morning_check_obj = CheckInInformation.objects.filter(check_time__range=[morning_check_time_start, morning_check_time_end], userCode=request.user.job_number)

            morning_off_work_time = datetime.strptime(end_time, date_format) + timedelta(hours=0.5)
            morning_off_work_obj = CheckInInformation.objects.filter(check_time__range=[morning_check_time_end, morning_off_work_time], userCode=request.user.job_number)

            if SchedulingObj.first().start_time1:
                try:
                    start_time1 = f'{duty_date} {SchedulingObj.first().start_time1}:00'
                    afternoon_work_end_time = datetime.strptime(start_time1, date_format) + timedelta(hours=0.5)
                    afternoon_work_end_obj = CheckInInformation.objects.filter(check_time__range=[morning_off_work_time, afternoon_work_end_time], userCode=request.user.job_number)

                    end_time1 = f'{duty_date} {SchedulingObj.first().end_time1}:00'
                    evening_work_end_time = datetime.strptime(end_time1, date_format) + timedelta(hours=2)
                    print(morning_off_work_time, afternoon_work_end_time)
                    print(afternoon_work_end_time, evening_work_end_time)
                    evening_work_end_obj = CheckInInformation.objects.filter(check_time__range=[afternoon_work_end_time, evening_work_end_time], userCode=request.user.job_number)
                except:
                    pass
        morning_off_work_list, morning_check_work_list, afternoon_work_list, evening_work_list = [], [], [], []
        if morning_off_work_obj:
            for off_work in morning_off_work_obj:
                morning_off_work_list.append(off_work.check_time.strftime("%Y-%m-%d %H:%M"))
        if morning_check_obj:
            for morning_check in morning_check_obj:
                morning_check_work_list.append(morning_check.check_time.strftime("%Y-%m-%d %H:%M"))
        if afternoon_work_end_obj:
            for afternoon_work in afternoon_work_end_obj:
                afternoon_work_list.append(afternoon_work.check_time.strftime("%Y-%m-%d %H:%M"))
        if evening_work_end_obj:
            for evening_work in evening_work_end_obj:
                evening_work_list.append(evening_work.check_time.strftime("%Y-%m-%d %H:%M"))
        returnDict = {'status': 'success', "message": "操作成功！", "code": 200, "morning_off_work_obj": morning_off_work_list, "morning_check_obj": morning_check_work_list,
                      "afternoon_work_end_obj": afternoon_work_list, "evening_work_end_obj": evening_work_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class department_statistics(View):
    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        days_in_month = calendar.monthrange(datetime.now().year, datetime.now().month)[1]
        objs = User.objects.filter(company=request.user.company, is_delete='0')
        data_list = []
        for i in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]:
            attendance_days = 0
            for j in range(1, days_in_month+1):
                if j < 10:
                    check_time_start = f'{datetime.now().strftime("%Y-%m")}-0{j} 00:00:00'
                    check_time_end = f'{datetime.now().strftime("%Y-%m")}-0{j} 23:59:59'
                else:
                    check_time_start = f'{datetime.now().strftime("%Y-%m")}-{j} 00:00:00'
                    check_time_end = f'{datetime.now().strftime("%Y-%m")}-{j} 23:59:59'
                if CheckInInformation.objects.filter(check_time__range=[check_time_start, check_time_end], userCode=i.job_number).count():
                    attendance_days += 1

            data_list.append({"real_name": i.real_name, "job_number": i.job_number, "company": i.company.name, "attendance_days": attendance_days})

        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class all_check_in_detail(View):
    def post(self, request):
        JobNumber = request.POST.get("job_number", 20)
        first_day_of_month = datetime(datetime.now().year, datetime.now().month, 1)
        year = datetime.now().year
        month = datetime.now().month
        _, last_day = calendar.monthrange(year, month)
        last_day = str(datetime.strptime(f'{year}-{month}-{last_day}', '%Y-%m-%d').date()) + " 23:59:59"
        objs = CheckInInformation.objects.filter(check_time__range=[first_day_of_month, last_day], userCode=JobNumber)
        user_obj = User.objects.get(job_number=JobNumber)
        data_list = [{'real_name': user_obj.real_name, 'job_number': JobNumber, 'check_time': obj.check_time.strftime("%Y-%m-%d %H:%M"), "check_date": obj.check_time.strftime("%Y-%m-%d")} for obj in objs]
        returnDict = {'status': 'success', "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")